package com.glodon.zhuanli.front.web;

import com.glodon.framework.web.util.ResponseParam;
import com.glodon.zhuanli.common.ZhuanliBaseController;
import com.glodon.zhuanli.common.sms.SMSRegisterCode;
import com.glodon.zhuanli.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@RequestMapping(ZhuanliRegisterController.BASE_PATH)
@Controller
public class ZhuanliRegisterController extends ZhuanliBaseController {

    public static final String VCODE_SESSION = "register_vcode" ;

    public static final String BASE_PATH = "/front/register" ;

    @Autowired
    private SysUserService sysUserService ;

    @GetMapping
    public ModelAndView register(){
        ModelAndView mv = new ModelAndView() ;
        mv.setViewName( BASE_PATH ) ;
        return mv ;
    }

    /**
     * 发送短信验证码
     * @param mobile
     * @return
     */
    @RequestMapping("vcode")
    @ResponseBody
    public ResponseParam registerVCode(@RequestParam String mobile){
        if( !isMobile( mobile ) ){
            return ResponseParam.fail().addMessage("手机号格式不正确");
        }

        //发送短信息
        SMSRegisterCode smsRegisterCode = zlsmsService.sendMessage( new SMSRegisterCode(mobile)) ;
        if( !smsRegisterCode.isSuccess() ){
            return ResponseParam.fail().addMessage( smsRegisterCode.getMessage() ) ;
        }

        String vcode = smsRegisterCode.getVcode() ;

        log.info("发送短信验证码 {} 到手机号 {}" , vcode , mobile ) ;

        //注册的验证码
        getHttpServletRequest().getSession().setAttribute( VCODE_SESSION , vcode ) ;

        return ResponseParam.success() ;
    }

}
